package com.bdqn.BookManage.servlet;

import com.bdqn.BookManage.biz.BookInfoBiz;
import com.bdqn.BookManage.biz.impl.BookInfoBizImpl;
import com.bdqn.BookManage.po.BookInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author : CP
 * @version: 1.0
 * @program : BookManage
 * @description : 新增图书信息处理器
 * @date : 2020-07-21 14:50
 **/
@WebServlet("/addBook")
public class AddBookInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    /**
     * 新增图书信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 设置编码集 */
        resp.setCharacterEncoding("GBK");
        req.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();

        /* 获取日期 */
        String bornDate = req.getParameter("bornDate");
        /* 将储存日期字符转换为Date类型 */
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(bornDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //声明图书信息类，获取图书的基本信息
        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookName(req.getParameter("bookName"));
        bookInfo.setPrice(Double.valueOf(req.getParameter("price")));
        bookInfo.setTypeId(Integer.valueOf(req.getParameter("typeId")));
        bookInfo.setBornDate(date);
        bookInfo.setImgUrl(req.getParameter("imgUrl"));
        bookInfo.setState(Integer.valueOf(req.getParameter("state")));
        bookInfo.setStock(Integer.valueOf(req.getParameter("stock")));

        //新增图书信息
        BookInfoBiz bookInfoBiz = new BookInfoBizImpl();
        boolean yes = bookInfoBiz.newBook(bookInfo);

        //处理结果
        String str = yes?"图书信息添加成功!":"网络繁忙~";
        out.print("<script>alert('"+str+"');location.href = '/BookManage/queryBook';</script>");
        out.flush();
        out.close();
    }
}
